package com.wyp.didishige.activity.dynamic;

import android.content.DialogInterface;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baidu.appx.BDBannerAd;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.utils.DistanceUtil;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.umeng.analytics.MobclickAgent;
import com.wyp.didishige.activity.BaseActivity;
import com.wyp.didishige.activity.ImageBrowserActivity;
import com.wyp.didishige.activity.users.UserInfoActivity;
import com.wyp.didishige.adapter.CommentAdapter;
import com.wyp.didishige.adapter.GridAdapter;
import com.wyp.didishige.bean.SendCommentMessage;
import com.wyp.didishige.config.Config;
import com.wyp.didishige.config.Constants;
import com.wyp.didishige.db.NewCommentManager;
import com.wyp.didishige.model.CommentV3;
import com.wyp.didishige.model.Dynamic;
import com.wyp.didishige.utils.DateUtil;
import com.wyp.didishige.utils.ImageLoadOptions;
import com.wyp.didishige.utils.IntentUtil;
import com.wyp.didishige.utils.StringUtils;
import com.wyp.didishige.utils.ToastUtil;
import com.wyp.didishige.wiget.ScrollNestGridView;
import com.wyp.didishige.wiget.xlist.XListView;
import com.wyp.didishige.R;
import com.wyp.didishige.model.User;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.bmob.newim.BmobIM;
import cn.bmob.newim.bean.BmobIMConversation;
import cn.bmob.newim.bean.BmobIMMessage;
import cn.bmob.newim.bean.BmobIMUserInfo;
import cn.bmob.newim.core.BmobIMClient;
import cn.bmob.newim.listener.MessageSendListener;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.datatype.BmobGeoPoint;
import cn.bmob.v3.datatype.BmobPointer;
import cn.bmob.v3.datatype.BmobRelation;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.DeleteListener;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.GetListener;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UpdateListener;
@SuppressWarnings("ALL")
public class DynamicDetailActivity extends BaseActivity implements XListView.IXListViewListener {
    TextView user_name;
    TextView publish_community;
    TextView publish_time;
    TextView user_request;
    TextView distance;
    TextView reply_info;
    TextView comment_count;
    TextView like_count;
    TextView read_count;
    TextView dynamic_address;

    EditText edit_comment;
    ImageView send;
    ImageView user_head;
    TextView user_gender;
    LinearLayout comment;
    LinearLayout comment_lay;
    LinearLayout like;

    User user, atUser;
    Dynamic dynamic;
    String dynamicid;
    String newCommentId;
    CommentAdapter commentAdapter;
    XListView commentList;

    ScrollNestGridView gridview_image;
    GridAdapter gridAdapter;
    BmobFile[] photos;

    ImageView vip_lv = null;
    ImageView delete = null;


    View headerView = null;
    String banner = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_request_detail_v2);
        actionBar = getSupportActionBar();
        assert actionBar != null;
        actionBar.setDisplayHomeAsUpEnabled(true);
        actionBar.setTitle("动态详情");

        Bundle bundle = getIntent().getExtras();
        dynamicid = bundle.getString(Constants.DYNAMIC_ID);
        newCommentId = bundle.getString(Constants.COMMENT_ID);
        user = BmobUser.getCurrentUser(this, User.class);
        banner = MobclickAgent.getConfigParams(this, "banner");
        if (!StringUtils.isNullOrEmpty(newCommentId)){
            NewCommentManager.getInstance(this).updateNewComment(newCommentId, Config.STATUS_VERIFY_READED);
        }
        initView();
        queryDynamic();
    }
    BDBannerAd bannerview;
    private void addBanner() {
        // 实例化广告条
        bannerview = new BDBannerAd(this,Config.baiduApiKey, Config.baiduPublisherId);
        bannerview.setAdSize(BDBannerAd.SIZE_FLEXIBLE); //选择模式
        bannerview.setAdListener(new BDBannerAd.BannerAdListener() {
            @Override
            public void onAdvertisementDataDidLoadSuccess() {
                System.out.println("onAdvertisementDataDidLoadSuccess");
            }

            @Override
            public void onAdvertisementDataDidLoadFailure() {
                System.out.println("onAdvertisementDataDidLoadFailure");

            }

            @Override
            public void onAdvertisementViewDidShow() {
                System.out.println("onAdvertisementViewDidShow");

            }

            @Override
            public void onAdvertisementViewDidClick() {
                System.out.println("onAdvertisementViewDidClick");

            }

            @Override
            public void onAdvertisementViewWillStartNewIntent() {
                System.out.println("onAdvertisementViewWillStartNewIntent");

            }
        });
        // 获取要嵌入广告条的布局
        RelativeLayout adLayout = (RelativeLayout) findViewById(R.id.adLayout);
//        if (banner.equals("true")){
        adLayout.setVisibility(View.VISIBLE);
//        }
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        params.addRule(RelativeLayout.CENTER_HORIZONTAL);
        bannerview.setLayoutParams(params);
        // 将广告条加入到布局中
        adLayout.addView(bannerview);
        adLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MobclickAgent.onEvent(DynamicDetailActivity.this, "dynamic_detail_banner_click");
            }
        });
    }

    private void initView() {
        gridview_image = (ScrollNestGridView) findViewById(R.id.gridview_image);

        edit_comment = (EditText) findViewById(R.id.edit_comment);
        send = (ImageView) findViewById(R.id.send_comment);

        comment_count = (TextView) findViewById(R.id.comment_count);
        like_count = (TextView) findViewById(R.id.like_count);
        read_count = (TextView) findViewById(R.id.read_count);

        reply_info = (TextView) findViewById(R.id.reply_info);
        vip_lv = (ImageView) findViewById(R.id.vip_lv);
        delete = (ImageView) findViewById(R.id.delete);
        user_name = (TextView) findViewById(R.id.user_name);
        publish_community = (TextView) findViewById(R.id.publish_community);
        distance = (TextView) findViewById(R.id.distance);
        publish_time = (TextView) findViewById(R.id.publish_time);
        user_request = (TextView) findViewById(R.id.dynamic_content);
        user_head = (ImageView) findViewById(R.id.user_head);
        user_gender = (TextView) findViewById(R.id.user_gender);
        dynamic_address = (TextView) findViewById(R.id.dynamic_address);
        comment_lay = (LinearLayout) findViewById(R.id.comment_lay);
        comment = (LinearLayout) findViewById(R.id.comment);
        like = (LinearLayout) findViewById(R.id.like);
        comment_count.setVisibility(View.VISIBLE);

        like.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                updateLikeCount();
            }
        });

        comment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                atUser = null;
                reply_info.setVisibility(View.GONE);
                edit_comment.requestFocus();
                showSoftInputView(v);
            }
        });
        delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                deleteThis();
            }
        });
        send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendComment();
            }
        });
        initListView();
        initGridView();
        queryLikes();
    }

    private void initGridView() {
        gridview_image.setVisibility(View.VISIBLE);
        gridAdapter = new GridAdapter(this, false);
        gridAdapter.setmNetList(null);
        gridview_image.setAdapter(gridAdapter);
        gridview_image.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Bundle bundle = new Bundle();
                ArrayList<BmobFile> fiile = new ArrayList<BmobFile>();
                for (BmobFile files :
                        photos) {
                    fiile.add(files);
                }
                bundle.putSerializable("photos", fiile);
                bundle.putInt("position", position);
                IntentUtil.start_activity(DynamicDetailActivity.this, ImageBrowserActivity.class, bundle);
            }
        });
    }

    private void initListView() {
        commentAdapter = new CommentAdapter(this, new ArrayList<CommentV3>());
        commentList = (XListView) findViewById(R.id.comments_list);
        commentList.setXListViewListener(this);
        commentList.setPullLoadEnable(true);
        commentList.setPullRefreshEnable(false);
        commentList.setAdapter(commentAdapter);
        commentList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                CommentV3 commentV3 = (CommentV3) commentAdapter.getItem(position);
                reply_info.setVisibility(View.VISIBLE);
                reply_info.setText("回复:" + commentV3.getCommentUser().getNick());
                atUser = commentV3.getCommentUser();
                edit_comment.requestFocus();
            }
        });
        commentList.startLoadMore();
    }

    private void deleteThis() {
        builder.setTitle("删除动态");
        builder.setMessage("确定删除此条动态");
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Dynamic dynamic = new Dynamic();
                dynamic.setObjectId(dynamicid);
                loading.setTitle("提示");
                loading.setMessage("正在删除动态...");
                loading.show();
                dynamic.delete(DynamicDetailActivity.this, new DeleteListener() {
                    @Override
                    public void onSuccess() {
                        setResult(RESULT_OK);
                        finish();
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                        loading.cancel();
                    }

                    @Override
                    public void onFailure(int i, String s) {
                        ToastUtil.showShort(DynamicDetailActivity.this, "操作失败," + s);
                    }
                });
                dialog.cancel();
            }
        });
        builder.show();
    }

    /**
     * 获取动态详情
     */
    private void queryDynamic() {
        BmobQuery<Dynamic> query = new BmobQuery<>();
        query.addWhereEqualTo("objectId", dynamicid);
        query.include("author,images");
        dynamic = new Dynamic();
        dynamic.setObjectId(dynamicid);
        query.addWhereRelatedTo("likes", new BmobPointer(dynamic));
        query.getObject(this, dynamicid, new GetListener<Dynamic>() {
            @Override
            public void onSuccess(Dynamic req) {

                if (req != null) {
                    comment_lay.setVisibility(View.VISIBLE);
                    dynamic = req;
                    updateReadCount();
                    addBanner();
                    BmobGeoPoint point = dynamic.getLocation();
                    if (point != null) {
                        LatLng ll = new LatLng(point.getLatitude(), point.getLongitude());
                        int meter = (int) DistanceUtil.getDistance(ll, new LatLng(user.getLocation().getLatitude(), user.getLocation().getLongitude()));
                        dynamic.setMeter(meter);
                    }

                    initUserInfo();
                } else {
                    ShowToast("请检测网络");
                }
            }

            @Override
            public void onFailure(int i, String s) {
                ShowToast("请检测网络");
            }
        });
    }

    private void queryLikes() {
        BmobQuery<User> query = new BmobQuery<User>();
        dynamic = new Dynamic();
        dynamic.setObjectId(dynamicid);
        //likes是Post表中的字段，用来存储所有喜欢该帖子的用户
        query.addWhereRelatedTo("likes", new BmobPointer(dynamic));
        query.findObjects(this, new FindListener<User>() {

            @Override
            public void onSuccess(List<User> object) {
                Log.i("life", "查询个数：" + object.size());
            }

            @Override
            public void onError(int code, String msg) {
                Log.i("life", "查询失败：" + code + "-" + msg);
            }
        });
    }

    /**
     * 评论
     */
    private void sendComment() {
        if (TextUtils.isEmpty(edit_comment.getText())) {
            ShowToast("写点什么吧");
            return;
        }
        final CommentV3 commentV3 = new CommentV3();
        commentV3.setCommentUser(user);
        commentV3.setDynamicId(dynamicid);
        if (atUser != null) {
            commentV3.setAtUser(atUser);
        }
        final String comment = edit_comment.getText().toString();
        commentV3.setContent(comment);
        commentV3.save(this, new SaveListener() {
            @Override
            public void onSuccess() {
                reply_info.setVisibility(View.GONE);
                edit_comment.setText("");
                edit_comment.clearFocus();
                hideSoftInputView();
                updateCommentCount();
                commentAdapter.add(commentV3);
                commentList.setFooterText("加载完毕");
                if (atUser != null) {
                    if (atUser.getObjectId().equals(user.getObjectId())) {
                        return;
                    }
                } else if (dynamic.getAuthor().getObjectId().equals(user.getObjectId())) {
                    return;
                }
                SendCommentMessage commentMessage = new SendCommentMessage();
                User currentUser = BmobUser.getCurrentUser(DynamicDetailActivity.this, User.class);
                Map<String, Object> map = new HashMap<>();
                map.put("name", currentUser.getNick());//发送者姓名，这里只是举个例子，其实可以不需要传发送者的信息过去
                map.put("avatar", currentUser.getAvatar());//发送者的头像
                map.put("dynamicId", dynamicid);//发送者的uid
                map.put("commentId",commentV3.getObjectId());
                //启动一个会话，如果isTransient设置为true,则不会创建在本地会话表中创建记录，
                //设置isTransient设置为false,则会在本地数据库的会话列表中先创建（如果没有）与该用户的会话信息，且将用户信息存储到本地的用户表中
                //构造聊天方的用户信息:传入用户id、用户名和用户头像三个参数
                BmobIMUserInfo info;
                if (atUser != null) {
                    info = new BmobIMUserInfo(atUser.getObjectId(), atUser.getNick(), atUser.getAvatar());
                    map.put("type", 1);
                    map.put("content", comment);
                } else {
                    info = new BmobIMUserInfo(dynamic.getAuthor().getObjectId(), dynamic.getAuthor().getNick(), dynamic.getAuthor().getAvatar());
                    map.put("content", dynamic.getContent());
                    map.put("type", 0);
                }

                commentMessage.setExtraMap(map);
                BmobIMConversation c = BmobIM.getInstance().startPrivateConversation(info, true, null);
                BmobIMConversation conversation = BmobIMConversation.obtain(BmobIMClient.getInstance(), c);
                conversation.sendMessage(commentMessage, new MessageSendListener() {
                    @Override
                    public void done(BmobIMMessage bmobIMMessage, BmobException e) {
                        if (bmobIMMessage != null) {

                        }
                    }
                });
            }

            @Override
            public void onFailure(int i, String s) {
                ShowToast("评论失败，请重试");
            }
        });

    }

    /**
     * 更新评论数量
     */
    private void updateCommentCount() {
        dynamic.setCommentNum(dynamic.getCommentNum() + 1);
        dynamic.update(this, new UpdateListener() {
            @Override
            public void onSuccess() {
                comment_count.setText(dynamic.getCommentNum() + "");
            }

            @Override
            public void onFailure(int i, String s) {

            }
        });
    }

    /**
     * 点赞
     */
    private void updateLikeCount() {
        BmobRelation relation = new BmobRelation();
        relation.add(user);
        dynamic.setLikes(relation);
        dynamic.update(DynamicDetailActivity.this, new UpdateListener() {
            @Override
            public void onSuccess() {

            }

            @Override
            public void onFailure(int i, String s) {

            }
        });
    }

    private void updateReadCount() {
        dynamic.setReadNum(dynamic.getReadNum() + 1);
        dynamic.update(this, new UpdateListener() {
            @Override
            public void onSuccess() {
                read_count.setText(String.format("%d", dynamic.getReadNum()));
            }

            @Override
            public void onFailure(int i, String s) {

            }
        });
    }

    /**
     * 显示信息
     */
    private void initUserInfo() {
        photos = dynamic.getImages();
        if (photos != null && photos.length != 0) {
            gridAdapter.setmNetList(photos);
        }

        if (!StringUtils.isNullOrEmpty(dynamic.getAddress())) {
            dynamic_address.setText(dynamic.getAddress());
        }
        final User dynamicAuthor = dynamic.getAuthor();
        if (dynamicAuthor != null) {
            if (dynamicAuthor.getObjectId().equals(user.getObjectId())) {
                delete.setVisibility(View.VISIBLE);
            }

            if (dynamicAuthor.getAvatar() == null) {
                user_head.setImageResource(R.drawable.ic_launcher);
                ImageLoader.getInstance().displayImage("drawable://" + R.drawable.ic_launcher, user_head,
                        ImageLoadOptions.avatarOptions);
            } else {
                ImageLoader.getInstance().displayImage(dynamicAuthor.getAvatar(), user_head, ImageLoadOptions.avatarOptions);
            }

            user_name.setText(dynamicAuthor.getNick());
            if (!StringUtils.isNullOrEmpty(dynamicAuthor.getCommunity())) {
                publish_community.setText(dynamicAuthor.getCommunity());
                publish_community.setVisibility(View.VISIBLE);
            } else {
                publish_community.setVisibility(View.GONE);
            }
            String age = "";
            if (DateUtil.getAge(dynamic.getAuthor().getUserBirthday()) > 0) {
                age = " " + DateUtil.getAge(dynamic.getAuthor().getUserBirthday()) + "";
            }

            user_gender.setText(age);

            if (dynamicAuthor.getSex() != null && dynamicAuthor.getSex()) {
                user_gender.setBackgroundResource(R.drawable.user_male_bg);
                user_gender.setCompoundDrawablesWithIntrinsicBounds(getResources().getDrawable(R.drawable.ic_user_male), null, null, null);
            } else {
                user_gender.setBackgroundResource(R.drawable.user_female_bg);
                user_gender.setCompoundDrawablesWithIntrinsicBounds(getResources().getDrawable(R.drawable.ic_user_famale), null, null, null);
            }

            int level = dynamic.getAuthor().getLevel();
            if (level >= 1 && level < 3) {
                vip_lv.setImageResource(R.drawable.vip_lv_1);
                vip_lv.setVisibility(View.VISIBLE);
            } else if (level >= 3 && level < 6) {
                vip_lv.setImageResource(R.drawable.vip_lv_3);
                vip_lv.setVisibility(View.VISIBLE);

            } else if (level >= 6 && level < 12) {
                vip_lv.setImageResource(R.drawable.vip_lv_6);
                vip_lv.setVisibility(View.VISIBLE);

            } else if (level >= 9) {
                vip_lv.setImageResource(R.drawable.vip_lv_12);
                vip_lv.setVisibility(View.VISIBLE);

            } else {
                vip_lv.setVisibility(View.GONE);
            }
            user_head.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Bundle bundle = new Bundle();
                    bundle.putString(Config.KEY_USER_ID, dynamicAuthor.getObjectId());

                    IntentUtil.start_activity(DynamicDetailActivity.this, UserInfoActivity.class, bundle);
                }
            });
        }


        double meter = dynamic.getMeter() / 1000;

        distance.setText(meter + "千米");

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        2015-04-22 23:54:13
        Date date = new Date();
        try {
            date = simpleDateFormat.parse(dynamic.getCreatedAt());
        } catch (ParseException e) {
            e.printStackTrace();
        }

        Calendar calendar = Calendar.getInstance();

        calendar.setTime(date);
        publish_time.setText(DateUtil.getDateSpan(calendar.getTimeInMillis() / 1000,
                DateUtil.getTimestamp(new Date())));
        user_request.setText(dynamic.getContent());
        comment_count.setText(String.format("%d", dynamic.getCommentNum()));
        like_count.setText(String.format("%d", dynamic.getLikeNum()));
        read_count.setText(String.format("%d", dynamic.getReadNum()));

    }

    @Override
    public void onRefresh() {

    }

    @Override
    public void onLoadMore() {
        loadComments();
    }

    int page = 0;
    int limit = 20;

    /**
     * 加载评论
     */
    private void loadComments() {
        BmobQuery<CommentV3> query = new BmobQuery<CommentV3>();
        query.addWhereEqualTo(Constants.DYNAMIC_ID, dynamicid);
        query.include("atUser,commentUser");
        query.setLimit(limit);
        query.setSkip(page * limit);
        query.findObjects(this, new FindListener<CommentV3>() {
            @Override
            public void onSuccess(List<CommentV3> commentV3s) {
                commentList.stopLoadMore();
                if (commentV3s != null && commentV3s.size() != 0) {
                    page++;
                    commentAdapter.appendToList(commentV3s);
                    if (commentV3s.size() < limit) {
                        commentList.setFooterText("加载完毕");
                        commentList.setPullLoadEnable(false);
                    }
                } else {
                    if (page == 0) {
                        commentList.setFooterText("暂无评论，快来抢沙发吧");
                    } else {
                        commentList.setPullLoadEnable(false);
                        commentList.setFooterText("加载完毕");
                    }
                }
            }

            @Override
            public void onError(int i, String s) {
                commentList.stopLoadMore();
                commentList.setFooterText("加载错误，请重试");
            }
        });
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}
